<!--公用icon组件
    使用方法: <star :score="4" :size="48"></star>,参数1: 得分  参数2: 容器尺寸
-->
<template>
  <div class="star" :class="starType">
    <span class="star-item" v-for="(starItem, index) in starItems" :class="starItem" :key="index"></span>
  </div>
</template>

<script>
const len = 5
const STAR_ON = 'on'
const STAR_OFF = 'off'
const STAR_HALF = 'half'

export default {
  name: 'star',
  props: {
    score: {
      type: Number,
      default: 0
    },
    size: {
      type: Number,
      default: 0
    }
  },
  computed: {
    starItems () {
      let result = []
      // 向下取整,获取得分整数,给整星
      let scoreCount = Math.floor(this.score) // 1.5 -> 1
      for (let i = 0; i < scoreCount; i++) {
        result.push(STAR_ON)
      }
      // 实际得分和取整的差值,大于一半,给半星
      let diff = this.score - scoreCount
      if (diff >= 0.5) {
        result.push(STAR_HALF)
      }
      // 获取当前剩余的星,再全部给暗星
      const noScoreLen = len - result.length
      for (let i = 0; i < noScoreLen; i++) {
        result.push(STAR_OFF)
      }
      return result
    },
    starType () {
      return 'star-' + this.size
    }
  }
}
</script>

<style lang="stylus" scoped>
@import "~assets/styles/mixin.styl"

.star
  display flex
  justify-content center
  align-items center
// 打星逻辑: div容器通过star-48后面数字来定位具体item,再每个item的class中通过组合(class='star-item on')形式,来显示不同星样式
.star-48
  .star-item
    width 20px
    height 20px
    background-size 20px 20px
    background-repeat: no-repeat
    margin-right 22px
    &:last-child
      margin-right 0
    &.on
      bg-image('/assets/images/star/star48_on')
    &.half
      bg-image('/assets/images/star/star48_half')
    &.off
      bg-image('/assets/images/star/star48_off')
.star-36
  .star-item
    width: 15px
    height: 15px
    margin-right: 6px
    background-size: 15px 15px
    &:last-child
      margin-right: 0
    &.on
      bg-image('/assets/images/star/star36_on')
    &.half
      bg-image('/assets/images/star/star36_half')
    &.off
      bg-image('/assets/images/star/star36_off')
.star-24
  .star-item
    width: 10px
    height: 10px
    margin-right: 6px
    background-size: 10px 10px
    &:last-child
      margin-right: 0
    &.on
      bg-image('/assets/images/star/star24_on')
    &.half
      bg-image('/assets/images/star/star24_half')
    &.off
      bg-image('/assets/images/star/star24_off')
</style>
